package io.github.talelin.latticy.common.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @authoer:wulongbo
 * @createDate:2022/5/31
 * @description:
 */
public class CharUtil {

    public static String subPathOver3(String path, String findText) {
        int count = CharUtil.appearNumber(path, findText);
        if (count <= 2) {
            return path;
        }
        int index = CharUtil.getIndex(path, findText, 3);
        return path.substring(0, index);
    }

    /**
     * 获取指定字符串出现的次数
     *
     * @param srcText  源字符串
     * @param findText 要查找的字符串
     * @return
     */
    public static int appearNumber(String srcText, String findText) {
        int count = 0;
        Pattern p = Pattern.compile(findText);
        Matcher m = p.matcher(srcText);
        while (m.find()) {
            count++;
        }
        return count;
    }

    /**
     * @param str     定义字符串 str
     * @param key     定义需要被查找的字符串
     * @param findKey 定义第N次出现
     * @return
     */
    public static int getIndex(String str, String key, int findKey) {

        //判断"Ab2Ad3A4"中"A"出现第二次的位置
        Pattern pattern = Pattern.compile(key);
        Matcher findMatcher = pattern.matcher(str);
        int number = 0;
        while (findMatcher.find()) {
            number++;
            if (number == findKey) {//当第k次出现时停止
                break;
            }
        }
        return findMatcher.start();//第k次出现的位置
    }

    public static String getKey(String obj, String key) {
        if (obj == null) {
            return "";
        }
        int f1 = obj.indexOf("(");
        if (f1 == -1) {
            return "";
        }
        int f2 = obj.indexOf(")");
        if (f2 == -1) {
            return "";
        }
        String sub = obj.substring(f1 + 1, f2);
        String[] objs = sub.split(",");
        if (objs == null) {
            return "";
        }
        for (int i = 0; i <= objs.length; i++) {
            if (objs[i].contains(key)) {
                return objs[i].substring(key.length() + 2);
            }
        }
        return "";
    }

}
